<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <style>
    div {
      text-align: center;
      line-height: 40px;
      color: #fff;
      background-color: rgb(63, 192, 243);
      border-radius: 20px;
      width: 80px;
      height: 40px;
      cursor: pointer;
    }
  </style>
  <!-- <script src="./xlsx.js"></script> -->
  <script src="https://cdn.bootcdn.net/ajax/libs/xlsx/0.17.0/xlsx.js"></script>

</head>

<body>
  <input class="input" type="file" style="display: none;" onchange="onchangeFn(this)"></input>
  <div onclick="clickFn()">上传xlsx</div>
  <script>

    let inp = document.querySelector('.input')
    function clickFn() {
      document.querySelector('.input').click()
    }
    function onchangeFn() {
      let file = inp.files[0]
      let failName = file.name.substr(file.name.lastIndexOf(".") + 1);
      if (failName === 'xls' || failName === 'xlsx') {
        importf(file, function (data) {
          let res = JSON.parse(data)
          let result = convertKey(res, { '姓名': 'name', '年龄': 'age', "性别": 'gender', '工作': 'job', '喜好': 'hobby' })
          console.log(result);
        })
      } else {
        console.log('文件类型错误');
      }
    }
    // 把xlsx表格中的中文名字转换成对应的英文
    function convertKey(arr, keyMap) {
      let tempString = JSON.stringify(arr);
      // console.log('tempString', tempString);
      for (var key in keyMap) {
        var reg = `/"${key}":/g`;
        // console.log('reg', reg);
        // console.log(eval(reg));
        tempString = tempString.replace(eval(reg), '"' + keyMap[key] + '":');
      }
      return JSON.parse(tempString);
    }
    const importf = (fail, cd) => { // 导入
      var wb;
      var rABS = false; // 是否将文件读取为二进制字符串
      if (!fail) {
        return;
      }
      var f = fail;
      var reader = new FileReader();
      reader.onload = function (e) {
        var data = e.target.result;
        if (rABS) {
          wb = XLSX.read(btoa(fixdata(data)), {// 手动转化
            type: 'base64'
          });
        } else {
          wb = XLSX.read(data, {
            type: 'binary'
          });
        }
        // wb.SheetNames[0]是获取Sheets中第一个Sheet的名字
        // wb.Sheets[Sheet名]获取第一个Sheet的数据
        if (cd) {
          cd(JSON.stringify(XLSX.utils.sheet_to_json(wb.Sheets[wb.SheetNames[0]])));
        }
      };
      if (rABS) {
        reader.readAsArrayBuffer(f);
      } else {
        reader.readAsBinaryString(f);
      }
    };
  </script>
</body>

</html>